﻿///Author: Alexander Persson
///License: MS-PL

using System;
using System.Data.Objects;
using System.Text.RegularExpressions;

namespace ap.DatabaseUtil.Helpers
{
    internal static class ObjectContextExtensions
    {
        /// <summary>
        /// Gets the TableName of the object
        /// </summary>
        /// <param name="context">The ObjectContext we want to use for query</param>
        /// <param name="toTest">The object we want to get the tablename for</param>
        /// <returns>The tablename</returns>
        public static string GetTableName(this ObjectContext context, object toTest)
        {
            var type = toTest.GetType();
            var result = typeof(ObjectContextExtensions).GetMethod("GetTableNameExt");
            result = result.MakeGenericMethod(type);
            var tableName = result.Invoke(context, new object[] { context });

            return (string)tableName;
        }

        /// <summary>
        /// Queries the ObjectContext for the tablename
        /// </summary>
        /// <typeparam name="T">The type of the object</typeparam>
        /// <param name="context">The ObjectContext to use</param>
        /// <returns>The tablename</returns>
        internal static string GetTableNameExt<T>(this ObjectContext context) where T : class
        {
            var sql = context.CreateObjectSet<T>().ToTraceString();
            var regex = new Regex("FROM (?<table>.*) AS");
            var match = regex.Match(sql);

            string table = match.Groups["table"].Value;
            return table;
        }
    }
}
